<?php

namespace app\ice\controller;
use think\Db;
use think\Loader;
use app\ice\model\Goods;
use app\ice\model\UserAddress;
use think\Exception;
class Address extends Init
{
    
    protected function _initialize()
    {
        parent::_initialize();
        $this->areaModel = Loader::model('Area');
        $this->userAddressModel = Loader::model('UserAddress');
    }


    public function index(){
        $param = input('post.');
        $result = $this->userAddressModel->getAddressDefalt($param);
	    return ['data' => $result, 'code' => 200, 'message' => '显示成功', 'status' => true];
    }

    public function detail(){
        $param = input('post.');
        $result = $this->userAddressModel->getAddressDetail($param);
        if($result){
            $result['provinceStr'] = $this->areaModel->getName($result['provinceId']);
            $result['cityStr'] = $this->areaModel->getName($result['cityId']);
            $result['areaStr'] = $this->areaModel->getName($result['districtId']);
            if($result['isDefault']){
                $result['isDefault'] = true;
            }else{
                $result['isDefault'] = false;
            }
            return ['data' => $result, 'code' => 200, 'message' => '显示成功', 'status' => true];
        }else{
            return ['data' => [], 'code' => 200, 'message' => '显示成功', 'status' => true];
        }
    }

    public function add(){
        $param = input('post.');
        $model = new UserAddress();
        if($param['isDefault']){
            $list = $this->userAddressModel->getAddressList($param);
            $data = collection($list)->toArray();
            foreach ($data as $key => &$value) {
                $value['isDefault'] = 0;
            }
            $model->saveAll($data);
            $result = $model->allowField(true)->isUpdate(false)->save($param);
        }else{
            $result = $model->allowField(true)->save($param);
        }
        return ['data' => $result, 'code' => 200, 'message' => '添加成功', 'status' => true];
    }

    public function update(){
        $param = input('post.');
        $model = new UserAddress();
        if($param['isDefault']){
            $list = $this->userAddressModel->getAddressList($param);
            $data = collection($list)->toArray();
            foreach ($data as $key => &$value) {
                $value['isDefault'] = 0;
            }
            $model->saveAll($data);
            $result = $model->allowField(true)->save($param, ['address_id' => $param['id']]);
        }else{
            $result = $model->allowField(true)->save($param, ['address_id' => $param['id']]);
        }
        return ['data' => $result, 'code' => 200, 'message' => '编辑成功', 'status' => true];
    }

    public function getList(){
        $param = input('post.');
        $result = $this->userAddressModel->getAddressList($param);
        return ['data' => $result, 'code' => 200, 'message' => '显示成功', 'status' => true];
    }

}
